<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocketDemo</title>
</head>
<body>
<h2>测试WebSocket</h2>
<input type="text" id="name" name="name" value="张三"/>
<button type="button" onclick="onOpen()">上线</button>
<button type="button" onclick="onClose()">下线</button>
<button type="button" onclick="send()">发送</button>
<table >
    <tr>
        <td>
            在线人数<span id="count">0</span>人
        </td>
    </tr>
</table>


<script src="/js/jquery-3.0.0.js"> </script>
<script>
    var socket;
    // 建立连接
    function onOpen() {
        let name = $("#name").val();
        let url = "ws://127.0.0.1:10086/ws/"+name;
        socket = new WebSocket(url);
        // 握手成功后，会自动调用该函数
        socket.onopen = function (event) {
            console.log("WebSocket:已连接")
        }

        // 后台发送的消息
        socket.onmessage = function (event) {
            console.log("后台发送消息");
            console.log(event.data);
            $("#count").html(event.data);

        }

        // 监听WebSocket关闭
        socket.onclose = function (event) {
            console.log("WebSocket:断开")
        }

        // 监听WebSocket异常
        socket.onerror = function (event) {
            console.log("WebSocket:发生错误")
        }
    }

    function send() {
        // 前台像后台发送消息
        socket.send("消息内容");
    }

    // 关闭连接
    function onClose(){
        socket.close();
    }


</script>
</body>
</html>